package com.foxmail.yusp.mycloud;

import android.content.Context;
import android.util.Log;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;

class MyMQTT {
    private final static String TOPIC = "esp8266_E142CD/rpc";
    private String subTopic = "/th";
    private String serverUri = "tcp://m13.cloudmqtt.com:18957";
    private String user;
    private String pass;
    private MqttAndroidClient mqttClient;
    private Context context;
    private String clientId = "mycloud";
    private StateListener stateListener;
    private MsgListener msgListener;

    MyMQTT(Context context, String subTopic, String serverUri, String user, String pass) {
        this.context = context;
        this.subTopic = subTopic;
        this.serverUri = serverUri;
        this.user = user;
        this.pass = pass;

        clientId += System.currentTimeMillis();
    }

    void connect() {
        mqttClient = new MqttAndroidClient(context, serverUri, clientId);
        mqttClient.setCallback(new MqttCallback() {
            @Override
            public void connectionLost(Throwable cause) {
                if (stateListener != null)
                    stateListener.stateListner("连接丢失");
            }

            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                Log.d("我", message.toString());
                final JSONObject object = new JSONObject(message.toString());
                if (msgListener != null)
                    msgListener.msgListner(object);
            }

            @Override
            public void deliveryComplete(IMqttDeliveryToken token) {
                if (stateListener != null)
                    stateListener.stateListner("发送完成");
            }
        });

        final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setAutomaticReconnect(true);
        mqttConnectOptions.setCleanSession(false);
        mqttConnectOptions.setUserName(user);
        mqttConnectOptions.setPassword(pass.toCharArray());

        try {
            mqttClient.connect(mqttConnectOptions, null, new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    //状态通知
                    if (stateListener != null)
                        stateListener.stateListner("连接成功");
                    //订阅
                    try {
                        mqttClient.subscribe(subTopic, 0, null, new IMqttActionListener() {
                            @Override
                            public void onSuccess(IMqttToken asyncActionToken) {
                                if (stateListener != null)
                                    stateListener.stateListner("订阅成功");
                            }

                            @Override
                            public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                                if (stateListener != null)
                                    stateListener.stateListner("订阅失败");
                            }
                        });
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Log.d("我", "connect failure");
                    if (stateListener != null)
                        stateListener.stateListner("连接失败");
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    // publish
    void pub(String topic, String msg) {
        try {
            MqttMessage mqttMessage = new MqttMessage();
            mqttMessage.setPayload(msg.getBytes());
            if (mqttClient.isConnected())
                mqttClient.publish(topic, mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
        }

    }

    void setStateListener(StateListener listener) {
        stateListener = listener;
    }

    void setMsgListener(MsgListener listener) {
        msgListener = listener;
    }

    void get_key(String key) {
        pub(TOPIC, "{\"args\": {\"key\":\"" + key + "\"}, " +
                "\"tag\": \"" + key + "\", \"method\": \"Config.Get\",\"src\": \"/th\"}");
    }

    void put_key(String key, String tag) {
        pub(TOPIC, "{\"args\":" + key +
                ",\"tag\": \"" + tag + "\", \"method\": \"Config.Set\",\"src\": \"/th\"}");
    }

    void save_config(boolean reboot) {

        pub(TOPIC, "{\"args\": {\"reboot\":" + reboot + "}, " +
                "\"tag\": \"reboot\", \"method\": \"Config.Get\",\"src\": \"/th\"}");
    }

    public interface StateListener {
        void stateListner(String state);
    }

    public interface MsgListener {
        void msgListner(JSONObject obj);
    }
//
}
